package com.csxy.systemmanager.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.csxy.systemmanager.entity.LoginUser;
import com.csxy.systemmanager.common.ResponseResult;
import com.csxy.systemmanager.entity.User;
import com.csxy.systemmanager.service.LoginService;
import com.csxy.systemmanager.utils.JwtUtil;
import com.csxy.systemmanager.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service("LoginService")
public class LoginServiceImpl implements LoginService {
    //注入authenticationManager
    @Autowired
    private AuthenticationManager authenticationManager;

    //注入redis的工具类
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //进行用户认证
        Authentication authenticate = authenticationManager.authenticate(auth);
        //认证是否成功
        //认证失败
        if(ObjectUtils.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }

        //认证通过
        //认证成功生成jwt
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        //根据用户id生成jwt
        String token = JwtUtil.createJwt(userId);
        //添加到map
        HashMap hashMap = new HashMap();
        hashMap.put("token",token);
        //将数据使用redis进行存储 key为userID 值为当前用户
        redisCache.setCacheObject("login:" + userId,loginUser);
        //将jwt返回
        return new ResponseResult<>(200,"登录成功",hashMap);
    }

    @Override
    public ResponseResult logout() {
        //拿到当前用户
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //删除redis中的内容 （uid）
        redisCache.deleteObject("login:" + loginUser.getUser().getId());
        return new ResponseResult(200,"注销成功");
    }
}
